// 首页分类
let url_js = require("../../utils/url.js");
var common_js = require("../../utils/common.js");
var const_js = require("../../utils/const.js");
var user_js = require("../../utils/user.js");
var sys_js = require("../../utils/system.js");
var cart_js = require("../../utils/cart.js");
var ubt_js = require("../../utils/ubt.js");
var name_js = require("../../utils/ubtButtonName.js");
var api = require("../../utils/apiRequest.js");
let notificationCenter = require('../../thridLib/WxNotificationCenter.js');

let sy, delta;

Page({
  data: {
    sysInfo: null,
    contentStatus: -1,
    pageScrollTop: 0,
    slideBarList: [],
    navBarList: [],
    userInfo: null,
    rotateAnimation: {
      data: null,
      animation: null,
      rotate: 0
    },
    secondLevelList: [], //根据一级分类id存储二级分类list
    goodsList: [], //存储所有二级分类的商品
    containerTouchmove: '',
    isAllCategoryShow: false,
    selectedInfo: {
      firstLevelIndex: 0,
      secondLevelIndex: 0,
      secondLevelId: '', //用于scrollView
      indexInfo: {
        curPage: 1,
        pageSize: 10,
        noMore: false
      },
      list: []
    },
    scrollInfo: {
      top: false,
    },
    goodsPropertyInfo: {
      pageShow: false, //页面展示
      dismiss: false, //手动设置隐藏，当属性页面隐藏完成后，pageShow设置false
    },
    addCartSelctedGoodsInfo: null,
    refresherTriggered: false, //自定义下拉刷新
    contentScrollTop: 0, //记录商品内容试图滑动的top,
    isBottom: false, //用于上拉加载更多
    isLoadMore: false,
    goodsScrollViewContentHeight: 0, //当前分类下的内容高度
    goodsItemHeight: 0, //计算item的高度
    footerHeight: 0, //计算footer的Height,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //业务埋点
    ubt_js.myPageView(common_js.currentPageName(), options);
    //1.禁止转发
    wx.hideShareMenu();
    //2.注册通知
    this.registNotification();
    //3.初始化数据
    this.initData(options);
    //4.获取数据
    this.requestToGetFrontCategoryLists(0);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //更新购物车数量，setTabBarBadge受限制
    cart_js.updateTabBarCount();
  },

  //初始化数据
  initData: function (res) {
    let tempUserInfo = user_js.userInfo();
    this.setData({
      sysInfo: sys_js.systemInfo(),
      userInfo: tempUserInfo
    });
  },

  //注册通知，当自提点切换的时候，更新数据
  registNotification: function () {
    var that = this;
    notificationCenter.addNotification(const_js.changeShopSucessNoti, that.changedShop, that);
  },

  //自提点切换
  changedShop: function () {
    //1.更新userInfo
    let tempUserInfo = user_js.userInfo();
    this.setData({
      userInfo: tempUserInfo
    });
    //2.刷新数据
    this.resetAllData(true);
    //3.request
    this.requestToGetFrontCategoryLists(0, true);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    //移除通知
    var that = this;
    notificationCenter.removeNotification(const_js.changeShopSucessNoti, that);
    // 业务埋点
    ubt_js.myPageViewOut(common_js.currentPageName());
  },

  //获取分类的数据
  requestToGetFrontCategoryLists: function (parentId, pullDownRefresh) {
    let data = {
      cityId: this.data.userInfo.ztd.cityId,
      code: user_js.getCode(),
      parentId: parentId,
      shopId: this.data.userInfo.ztd.shopId
    }
    api.wxRequest(url_js.frontCategoryListUrl, data).then(res => {
      this.handleFrontCategoryListData(res, parentId, pullDownRefresh);
      common_js.hidePageLoading(pullDownRefresh);
    }).catch(err => {
      common_js.hidePageLoading(pullDownRefresh);
      common_js.log(err);
    });
  },

  //处理返回的分类数据
  handleFrontCategoryListData: function (res, parentId, pullDownRefresh) {
    var tmpList = res.result;

    //一级分类
    if (parentId == 0) {
      if (tmpList.length == 0) {
        common_js.showToast("分类为空！");
        return;
      }
      //
      var firstSubItem = tmpList[0];
      this.requestToGetFrontCategoryLists(firstSubItem.id);
      this.setData({
        slideBarList: tmpList
      });
    } else {
      //存储数据
      var tempSecondLevelMap = new Map(this.data.secondLevelList);
      if (tmpList.length > 0) {
        tempSecondLevelMap.set(parentId, tmpList);

        var firstSubItem = tmpList[0];
        this.requestToGetProductList(firstSubItem.id, 1, 10);
      } else {
        //存储数据
        tempSecondLevelMap.set(parentId, []);
      }
      //二级分类
      this.setData({
        secondLevelList: [...tempSecondLevelMap],
        navBarList: (tmpList ? tmpList : [])
      });
    }
  },

  //刷新重置数据
  resetAllData(pullDownRefresh) {
    if (!pullDownRefresh) return;
    //
    var tmpSlideBarList = this.data.slideBarList;
    tmpSlideBarList = [];
    var tmpNavBarList = this.data.navBarList;
    tmpNavBarList = [];
    var tmpSecondLevelList = this.data.secondLevelList;
    tmpSecondLevelList = [];
    var tmpGoodsList = this.data.goodsList;
    tmpGoodsList = [];

    var tmpSelectInfo = this.data.selectedInfo;
    tmpSelectInfo.firstLevelIndex = 0;
    tmpSelectInfo.secondLevelIndex = 0;
    tmpSelectInfo.secondLevelId = '';
    tmpSelectInfo.indexInfo.curPage = 1;
    tmpSelectInfo.indexInfo.pageSize = 10;
    tmpSelectInfo.indexInfo.noMore = false;
    tmpSelectInfo.list = [];

    var tmpScrollInfo = this.data.scrollInfo;
    tmpScrollInfo.top = 0;

    this.setData({
      slideBarList: tmpSlideBarList,
      navBarList: tmpNavBarList,
      secondLevelList: tmpSecondLevelList,
      goodsList: tmpGoodsList,
      containerTouchmove: '',
      selectInfo: tmpSelectInfo,
      isAllCategoryShow: false,
      scrollInfo: tmpScrollInfo,
      contentScrollTop: 0,
      isBottom: false,
      isLoadMore: false,
    });

    this.setCustomRefresherTriggered(false);
  },


  //获取产品列表
  requestToGetProductList: function (categoryId, curPage, pageSize, pullDownRefresh) {
    let data = {
      categoryId: categoryId,
      cityId: this.data.userInfo.ztd.cityId,
      code: user_js.getCode(),
      curPage: curPage,
      pageSize: pageSize,
      shopId: this.data.userInfo.ztd.id
    }
    api.wxRequest(url_js.productListUrl, data).then(res => {
      this.handleProductListData(res, categoryId, curPage, pageSize, pullDownRefresh);
    }).catch(err => {
      this.setCustomRefresherTriggered(false);
      common_js.log(err);
    });
  },

  //处理返回的商品数据
  handleProductListData: function (res, categoryId, curPage, pageSize, pullDownRefresh) {
    var tmpList = res.result;
    //selctedGoodsInfo
    var tmpSelectedInfo = this.data.selectedInfo;
    //
    var obj = {};
    var indexInfo = {
      curPage: curPage,
      pageSize: pageSize,
      noMore: false
    };
    if (res.page.pages <= curPage) {
      indexInfo.noMore = true;
    } else {
      indexInfo.curPage++;
    }
    obj.indexInfo = indexInfo;

    var tempGoodsMap = new Map(this.data.goodsList);
    if (tmpList && tmpList.length > 0) {
      var tmpPreList = [];
      if (tempGoodsMap.get(categoryId)) {
        tmpPreList = tempGoodsMap.get(categoryId).list;
      }
      obj.list = tmpPreList.concat(tmpList);
      tmpSelectedInfo.secondLevelId = tmpList[0].id;
    } else {
      obj.list = [];
    }

    tempGoodsMap.set(categoryId, obj);
    tmpSelectedInfo.indexInfo = indexInfo;
    tmpSelectedInfo.list = obj.list;
    tmpSelectedInfo.secondLevelId = categoryId;

    var tmpScrollInfo = this.data.scrollInfo;
    if (curPage == 1) {
      tmpScrollInfo.top = 0
    } else {
      tmpScrollInfo.top = this.data.contentScrollTop;
    }

    this.setData({
      selectedInfo: tmpSelectedInfo,
      contentStatus: 1,
      goodsList: [...tempGoodsMap],
      scrollInfo: tmpScrollInfo
    });
    console.log("数据返回，slectInfo设置之后")
    console.log(this.data.selectedInfo)
    console.log(this.data.goodsList);

    //重置状态
    if (pullDownRefresh) {
      this.setCustomRefresherTriggered(false);
    }
    //计算goodsScrollViewHeight----只需要计算一次
    this.getGoodsScrollViewContentHeight();
    //计算商品列表的高度
    this.getGoodsItemHeight();
    //计算footer
    this.getFooterHeight();
    //初始化bottomStatus
    this.initIsBottomStatus();
  },

  //按钮点击事件
  //禁止滚动
  preventTouchMove: function () { },

  //点击事件
  onSliderBarItem: function (e) {
    var index = e.currentTarget.dataset.index;
    var tmpSelectedInfo = this.data.selectedInfo;
    if (index == tmpSelectedInfo.firstLevelIndex) return;

    tmpSelectedInfo.firstLevelIndex = index;
    tmpSelectedInfo.secondLevelIndex = 0; //重置

    this.setData({
      selectedInfo: tmpSelectedInfo
    });

    //请求数据
    var firstLevelItem = this.data.slideBarList[index];
    var tempSecondLevelMap = new Map(this.data.secondLevelList);
    var secondLevellist = tempSecondLevelMap.get(firstLevelItem.id);
    if (!secondLevellist) {
      this.requestToGetFrontCategoryLists(firstLevelItem.id);
    } else {
      var tmpScrollInfo = this.data.scrollInfo;
      tmpScrollInfo.top = 0;

      var tmpGoodsMap = new Map(this.data.goodsList);
      var tmpGoodsInfo = tmpGoodsMap.get(secondLevellist[0].id);
      tmpSelectedInfo.secondLevelId = secondLevellist[0].id;
      tmpSelectedInfo.indexInfo = tmpGoodsInfo.indexInfo;
      tmpSelectedInfo.list = tmpGoodsInfo.list;

      this.setData({
        isAllCategoryShow: false,
        containerTouchmove: '',
        selectedInfo: tmpSelectedInfo,
        navBarList: secondLevellist,
        scrollInfo: tmpScrollInfo
      });

      //初始化bottomStatus
      this.initIsBottomStatus();
    }
    //
    this.onRightContentTap();
  },

  //点击二级分类
  onCategery: function (e) {
    var index = e.currentTarget.dataset.index;
    var tmpSelectedInfo = this.data.selectedInfo;
    if (index == tmpSelectedInfo.secondLevelIndex) return;

    tmpSelectedInfo.secondLevelIndex = index;

    //scrollInfo
    var tmpScrollInfo = this.data.scrollInfo;

    //根据一级和二级分类去请求数据
    var secondLevelItem = this.data.navBarList[index];
    tmpSelectedInfo.secondLevelId = secondLevelItem.id;

    var tempGoodsMap = new Map(this.data.goodsList);
    var tmpSelectedItem = tempGoodsMap.get(secondLevelItem.id);
    if (!tmpSelectedItem) {
      var navItem = this.data.navBarList[index];
      this.requestToGetProductList(navItem.id, 1, 10);
    } else {
      tmpScrollInfo.top = 0;
      tmpSelectedInfo.list = tmpSelectedItem.list;
    }
    //
    this.setData({
      selectedInfo: tmpSelectedInfo,
      scrollInfo: tmpScrollInfo
    });
    //初始化bottomStatus
    this.initIsBottomStatus();
  },


  //点击展开的二级分类
  onShowCategory: function (e) {
    this.onCategery(e);
    this.onMoreCategory();
  },

  //点击更多二级分类
  onMoreCategory: function (e) {
    //展示弹窗
    //动画
    if (!this.data.rotateAnimation.animation) {
      var tempRotateAnimation = this.data.rotateAnimation;
      var animation = wx.createAnimation({
        timingFunction: 'ease',
      });
      tempRotateAnimation.animation = animation;
      this.setData({
        rotateAnimation: tempRotateAnimation
      });
    }
    var tempRotateAnimation = this.data.rotateAnimation;
    var tempRotate = (tempRotateAnimation.rotate == -180) ? 0 : -180;
    tempRotateAnimation.rotate = tempRotate;
    tempRotateAnimation.animation.rotate(tempRotate).step();
    tempRotateAnimation.data = tempRotateAnimation.animation.export();
    this.setData({
      rotateAnimation: tempRotateAnimation
    });

    //展示
    if (this.data.isAllCategoryShow) {
      this.setData({
        isAllCategoryShow: false,
        containerTouchmove: ''
      });
    } else {
      this.setData({
        isAllCategoryShow: true,
        containerTouchmove: 'preventTouchMove'
      });
    }
  },

  //
  onAllCategoryCatchTap: function () { },

  onRightContentTap: function () {
    if (this.data.isAllCategoryShow) {
      this.onMoreCategory();
    }
  },

  //添加商品
  onGoodsAdd: function (e) {
    if (!user_js.isLogin()) {
      wx.navigateTo({
        url: '../loginIndex/loginIndex'
      });
      return
    }

    var index = e.currentTarget.dataset.index;
    var item = this.data.selectedInfo.list[index];
    if (item.skuList && item.skuList.length > 1) {
      if (item.dimensions.length == 0) {
        common_js.showToast("商品多规格属性不存在！");
        return;
      }
      //多规格,选择规格加入购物车
      //展示多规格商品
      var tmpGoodsPropertyInfo = this.data.goodsPropertyInfo;
      tmpGoodsPropertyInfo.pageShow = true;
      this.setData({
        goodsPropertyInfo: tmpGoodsPropertyInfo,
        addCartSelctedGoodsInfo: item,
        containerTouchmove: 'preventTouchMove'
      });
    } else {
      //单一规格,直接添加购物车
      if (item.skuList == 0) {
        common_js.showToast("商品sku不存在");
        return;
      }
      //限时抢购单独判断
      if (item.type == 2) {
        var skuItem = item.skuList[0];
        var cartLimitCount = cart_js.limitSkuCountWithSkuId(skuItem.id);
        var isAlert = (cartLimitCount == 0) ? (item.count > skuItem.userBuyLimit) : (cartLimitCount >= skuItem.userBuyLimit);
        if (isAlert) {
          common_js.showModal("每人限购" + skuItem.userBuyLimit + "件，超过的件数将以原价支付！", null, true, null, "我知道了", () => {
            this.requestToAddCart(item.skuList[0], item.id, item.skuList[0].id, 1);
          })
          return;
        }
      }
      this.requestToAddCart(item.skuList[0], item.id, item.skuList[0].id, 1);
    }

    //埋点
    ubt_js.myClickButton(common_js.currentPageName(), name_js.categoryAdd);
  },

  //商品属性选择确定
  onGoodsPropertyEnsure: function (e) {
    //消失
    this.onGoodsPropertyHidden();
    //添加购物车
    if (e) {
      var item = e.detail;
      //限时抢购单独判断
      if (this.data.addCartSelctedGoodsInfo.type == 2) {
        var skuItem = item.sku;
        var cartLimitCount = cart_js.limitSkuCountWithSkuId(skuItem.id);
        var isAlert = (cartLimitCount == 0) ? (item.count > skuItem.userBuyLimit) : (cartLimitCount >= skuItem.userBuyLimit);
        if (isAlert) {
          common_js.showModal("每人限购" + skuItem.userBuyLimit + "件，超过的件数将以原价支付！", null, true, null, "我知道了", () => {
            this.requestToAddCart(item.sku, this.data.addCartSelctedGoodsInfo.id, item.sku.id, item.count);
          })
          return;
        }
      }
      this.requestToAddCart(item.sku, this.data.addCartSelctedGoodsInfo.id, item.sku.id, item.count);
    }
  },

  //增加购物车
  requestToAddCart: function (skuItem, productId, skuId, num) {
    let data = {
      cityId: this.data.userInfo.ztd.cityId,
      code: user_js.getCode(),
      num: num,
      productId: productId,
      shopId: this.data.userInfo.ztd.id,
      skuId: skuId
    };
    api.wxRequest(url_js.cartAddUrl, data).then(res => {
      this.handleAddCartData(res, skuItem, skuId, num);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理添加购物车
  handleAddCartData: function (res, skuItem, skuId, num) {
    cart_js.addCart(skuItem, skuId, num);
    common_js.showToast("添加购物车成功");
  },

  //商品属性选择
  onGoodsPropertyHidden: function (e) {
    var tmpGoodsPropertyInfo = this.data.goodsPropertyInfo;
    tmpGoodsPropertyInfo.pageShow = false;
    tmpGoodsPropertyInfo.dismiss = false,
      this.setData({
        containerTouchmove: '',
        goodsPropertyInfo: tmpGoodsPropertyInfo
      });
  },

  //隐藏商品属性页面
  onHidePropertyPageView: function (e) {
    var tmpGoodsPropertyInfo = this.data.goodsPropertyInfo;
    tmpGoodsPropertyInfo.dismiss = true;
    this.setData({
      goodsPropertyInfo: tmpGoodsPropertyInfo
    });
  },

  //商品详情
  onGoodsDetail: function (e) {
    //埋点
    ubt_js.myClickButton(common_js.currentPageName(), name_js.categoryList);
    var index = e.currentTarget.dataset.index;
    var item = this.data.selectedInfo.list[index];
    wx.navigateTo({
      url: '../goodsDetails/goodsDetails?productId=' + item.id
    });
  },

  //初始化isBottom
  initIsBottomStatus: function (e) {
    wx.createSelectorQuery().select('.placeholder-c').fields({
      scrollOffset: true,
      size: true
    }, rect => {
      console.log(rect);
      if (rect && rect.height > 1) {
        this.setData({
          isBottom: true,
          isLoadMore: true
        })
      } else {
        this.setData({
          isBottom: false
        })
      }
    }).exec();
  },

  /**
   * 滑动中
   */
  scroll: function (e) {
    this.setData({
      contentScrollTop: e.detail.scrollTop
    })
  },

  //商品列表滚动到底部
  bindContentScrollEnd: function (e) {
    if (this.data.selectedInfo.indexInfo.noMore) {
      this.setData({
        isBottom: true
      })
      return;
    }
    console.log("商品加载更多");
    console.log(this.data.selectedInfo);
    console.log(this.data.goodsList);

    //请求数据
    var item = this.data.navBarList[this.data.selectedInfo.secondLevelIndex];
    this.requestToGetProductList(item.id, this.data.selectedInfo.indexInfo.curPage, this.data.selectedInfo.indexInfo.pageSize);
  },

  //重置scrollTop 
  resetContentScrollTop: function () {
    if (this.data.contentScrollTop == 0) return;

    //滚动结束，弹回顶部
    common_js.showLoading();
    var tmpScrollInfo = this.data.scrollInfo;
    tmpScrollInfo.top = 0;
    var timerItem = setTimeout(() => {
      this.setData({
        scrollInfo: tmpScrollInfo,
      })
      common_js.hideLoading();
      clearTimeout(timerItem);
    }, 666);
  },

  //getGoodsScrollViewContentHeight
  getGoodsScrollViewContentHeight: function () {
    if (this.data.goodsScrollViewContentHeight > 0) return;
    wx.createSelectorQuery().select('.goods-scroll-view').fields({
      scrollOffset: true,
      size: true
    }, rect => {
      if (rect && rect.height) {
        this.setData({
          goodsScrollViewContentHeight: rect.height
        })
      }
    }).exec();
  },
  //获取当前商品列表的高度
  getGoodsItemHeight: function () {
    if (this.data.footerHeight > 0) return;
    wx.createSelectorQuery().select('.item').boundingClientRect(rect => {
      if (rect && rect.height) {
        this.setData({
          goodsItemHeight: rect.height
        })
      }
    }).exec();
  },

  //获取当前tab下所有商品的高度
  getFooterHeight: function () {
    if (this.data.footerHeight > 0) return;
    wx.createSelectorQuery().select('.footer').boundingClientRect(rect => {
      if (rect && rect.height) {
        this.setData({
          footerHeight: rect.height
        })
      }
    }).exec();
  },

  // 监听用户滑动页面事件
  onPageScroll: function (e) {
    var topY = e.scrollTop + "px";
    this.setData({
      pageScrollTop: topY
    });
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    //重置数据
    this.resetAllData(true);
    // //3.request
    this.requestToGetFrontCategoryLists(0, true);
  },

  //当前商品的下拉刷新
  onGoodsPullDownRefresh: function (resetTriggered) {
    //update  triggered
    if (!resetTriggered) {
      this.setCustomRefresherTriggered(true);
    }
    //refresh
    var navItem = this.data.navBarList[this.data.selectedInfo.secondLevelIndex];
    //reset data
    var tmpSelectInfo = this.data.selectedInfo;
    tmpSelectInfo.secondLevelId = '';
    tmpSelectInfo.indexInfo.curPage = 1;
    tmpSelectInfo.indexInfo.pageSize = 10;
    tmpSelectInfo.indexInfo.noMore = false;
    tmpSelectInfo.list = [];
    var tempGoodsMap = new Map(this.data.goodsList);
    if (tempGoodsMap.get(navItem.id)) {
      tempGoodsMap.delete(navItem.id);
    }
    this.setData({
      selectedInfo: tmpSelectInfo,
      goodsList: [...tempGoodsMap]
    });
    //
    console.log("商品刷新");
    console.log(this.data.selectedInfo);
    console.log(this.data.goodsList);
    //请求数据
    this.requestToGetProductList(navItem.id, 1, 10, true);
  },

  //设置自定义下拉刷新状态
  setCustomRefresherTriggered: function (triggered) {
    this.setData({
      refresherTriggered: triggered
    });
  },

  /**
   * 手指按下
   */
  start: function (e) {
    if (!(this.data.selectedInfo.indexInfo.noMore && this.data.isBottom)) return;
    sy = e.changedTouches[0].pageY; //记录鼠标的位置
  },

  /**
  * 手指移动
  */
  move: function (e) {
    if (!(this.data.selectedInfo.indexInfo.noMore && this.data.isBottom)) return;
    if (sy) {
      let st = e.changedTouches[0].pageY;
      delta = st - sy;
      if (this.data.isBottom && delta < 0) {
        this.setData({//显示下拉刷新图标
          isLoadMore: true
        })
      }
    }
  },

  /**
   * 抬起手指
   */
  end: function (e) {
    if (!(this.data.selectedInfo.indexInfo.noMore && this.data.isBottom)) return;

    //处理特殊情况
    let st = e.changedTouches[0].pageY;
    delta = st - sy;

    if (delta < 0 && Math.abs(delta) > 150 && this.data.isLoadMore) {
      this.setData({//显示下拉刷新图标
        isLoadMore: false,
        isBottom: false
      })
      //上拉加载
      //1.切换当前一级类目下的下一个类目
      if (this.data.selectedInfo.secondLevelIndex < (this.data.navBarList.length - 1)) {
        var obj = {};
        obj.currentTarget = {};
        obj.currentTarget.dataset = {};
        obj.currentTarget.dataset.index = this.data.selectedInfo.secondLevelIndex + 1;
        this.onCategery(obj);
      } else {
        if ((this.data.slideBarList.length - 1) == this.data.selectedInfo.firstLevelIndex && (this.data.navBarList.length - 1) == this.data.selectedInfo.secondLevelIndex) {
          common_js.showToast("已经切换至最后一个类目");
          return;
        }
        //切换下一个一级类目
        var obj = {};
        obj.currentTarget = {};
        obj.currentTarget.dataset = {};
        obj.currentTarget.dataset.index = this.data.selectedInfo.firstLevelIndex + 1;
        this.onSliderBarItem(obj);
      }

      this.resetContentScrollTop();
    } else {
      this.setData({
        isBottom: false
      })
    }
  }
});